using System;

namespace armcontrolgui
{
	public partial class ScriptEditor : Gtk.Window
	{
		private ArmController ac_CurrentArm;
		private System.Threading.Thread th_RunningScript;
		public ScriptEditor (ArmController Arm) : base(Gtk.WindowType.Toplevel)
		{
			this.Build ();
			
			this.ac_CurrentArm = Arm;
			//this.ScriptTextView.Buffer.
		}
		
		public ScriptEditor (ArmController Arm, string FilePath) : this(Arm)
		{
			
		}
		
		public static void OpenFile(ArmController Arm)
		{
			using (Gtk.FileChooserDialog SelectFile = new Gtk.FileChooserDialog("Open script",
			                                                                    null,
			                                                                    Gtk.FileChooserAction.Open,
			                                                                    Gtk.Stock.Open, Gtk.ResponseType.Accept,
			                                                                    Gtk.Stock.Cancel, Gtk.ResponseType.Cancel
			                                                                    )){
				
				//TODO open in User Script folder.
				SelectFile.SetCurrentFolder(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
				
				SelectFile.Filter = new Gtk.FileFilter();
				SelectFile.Filter.AddPattern("*.ArmScript");
				
				if(SelectFile.Run() == (int)Gtk.ResponseType.Accept)
					new ScriptEditor(Arm, SelectFile.Filename);
			
				SelectFile.Destroy();
			}
		}
		
		protected virtual void OpenScriptEvent (object sender, System.EventArgs e)
		{
			ScriptEditor.OpenFile(this.ac_CurrentArm);
		}
		
		protected virtual void ExecuteEvent (object sender, System.EventArgs e)
		{
			if(this.th_RunningScript == null || this.th_RunningScript.Join(0))
				this.th_RunningScript = this.ac_CurrentArm.ScriptRun(this.ScriptTextView.Buffer.Text);
		}
		
		protected virtual void ScriptStopEvent (object sender, System.EventArgs e)
		{
			this.th_RunningScript.Abort();
		}
		
	}
}
